# -*- encoding:UTF-8 -*-
# desc: epkg translate
# create time: 20250117

import argparse
import subprocess
import sys
import os


def epkg_translate(args):
    """利用rpm2epkg工具转换包
    """
    epkg_home="/lkp/epkg/rpm2epkg"
    in_repo = args.in_repo_dir
    out_path = os.environ.get("out_path","")
    os_type = os.environ.get("os")
    os_version = os.environ.get("os_version")
    os_arch = os.environ.get("os_arch")
    if out_path == "":
        out_path = "/lkp/{0}/{1}/{2}/epkg".format(os_type,
                                                  os_version, os_arch)
    if not os.path.exists(out_path):
        os.makedirs(out_path)
    content = "{0} {1}\n".format(in_repo, out_path)
    repo_file = "{0}-{1}-{2}".format(os_type,os_version, os_arch)
    repo_file_path = "{0}/{1}".format(epkg_home, repo_file)
    with open(repo_file_path,'w') as file:
        file.write(content)
    translate_cmd = ["./batch-convert-rpm2epkg", "{0}".format(repo_file)]
    result = subprocess.run(translate_cmd, cwd=epkg_home,
            text=True, stdout=sys.stdout, stderr=sys.stderr)
    if result.returncode != 0:
        print("epkg translate failed:{0}".format(result.stderr))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="epkg转换")
    parser.add_argument("-in_repo_dir", required=True,default="",
                        help="rpm包输入路径")
    parser.add_argument("-rpm_name", required=True,default="", help="rpm包名")
    args = parser.parse_args()
    ret = epkg_translate(args)
